import axios, { AxiosError } from "axios";
import { ResultCodeEnum } from "@/enums/requestEnum";
import { TOKEN_KEY } from "@/enums/cacheEnum";
import feedback from "@/utils/feedBack";
import adapter from "./adapter.js";
const headers = {
	"Content-Type": "application/json",
};
const instance = axios.create({
	adapter,
	// 请求超时的毫秒数
	timeout: 10 * 1000,
	// 基础接口地址
	baseURL: appConfig.apiUrl,
	// 请求头
	headers: headers,
	// 自定义请求配置项
	requestOptions: {
		// 是否返回默认的响应
		isReturnDefaultResponse: false,
	},
});

// 方法重写
["delete", "get", "head", "options"].forEach((method) => {
	instance[method] = (url, params, config) => {
		return instance.request({
			...(config || {}),
			method: method,
			url: url,
			params: params || {},
		});
	};
});

// 请求拦截器
instance.interceptors.request.use(
	(config) => {
		config.headers.TOKEN = cache.get(TOKEN_KEY);
		return config;
	},
	(error) => Promise.reject(error),
);

// 响应拦截器
instance.interceptors.response.use(
	(response) => {
		const { isReturnDefaultResponse } = response.config.requestOptions;

		// 返回默认的响应
		if (isReturnDefaultResponse) {
			return response;
		}

		const { data } = response;
		switch (data.code) {
			case ResultCodeEnum.FAIL:
				feedback.toast(data.msg);
				return Promise.reject(response);
			case ResultCodeEnum.TOKEN_EXPIRE:
				feedback.toast("登录状态失效，请重新登录！");
				cache.clear()
				uni.redirectTo({
					url: "/pages/login/index",
				});
				return Promise.reject(response);
		}
		return data;
	},
	(error) => {
		let errMessage = "";

		if (error instanceof AxiosError) {
			switch (error.code) {
				case AxiosError.ERR_NETWORK:
					errMessage = "网络异常，请检查您的网络连接是否正常!";
					break;
				case AxiosError.ECONNABORTED:
					errMessage = "拒绝访问!";
					if (error.message.indexOf("timeout") > -1) {
						errMessage = "接口请求超时!";
					}
					break;
				case AxiosError.ETIMEDOUT:
					errMessage = "接口请求超时!";
					break;
			}
		}
		if (!errMessage) {
			switch (error?.response?.status) {
				case 400:
					errMessage = "错误请求!";
					break;
				case 401:
					errMessage = "未授权!";
					break;
				case 403:
					errMessage = "访问被禁止!";
					break;
				case 404:
					errMessage = "网络请求错误，未找到该资源!";
					break;
				case 405:
					errMessage = "网络请求错误，请求方法未允许!";
					break;
				case 500:
					errMessage = "服务器开小差啦!";
					break;
				case 501:
					errMessage = "网络未实现!";
					break;
				case 502:
					errMessage = "网络错误!";
					break;
				case 503:
					errMessage = "服务不可用，服务器暂时过载或维护!";
					break;
			}
		}

		if (errMessage) {
			feedback.toast(errMessage);
		}

		return Promise.reject(error);
	},
);

export default instance;
